package com.promote.hotspot.server.netty.pusher;

import com.google.common.collect.Queues;
import com.promote.hotspot.server.netty.dashboard.DashboardHolder;
import org.apache.commons.collections.CollectionUtils;
import org.promote.hotspot.common.model.HotKeyModel;
import org.promote.hotspot.common.tool.FastJsonUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 将热key推送到dashboard供入库
 *
 * @author enping.jep
 * @date 2024/01/18 16:25
 **/
@Component
public class DashboardPusher implements IPusher {

    private static LinkedBlockingQueue<HotKeyModel> queue = new LinkedBlockingQueue<>();

    @Override
    public void push(HotKeyModel model) {
        queue.offer(model);
    }

    @PostConstruct
    public void uploadToDashboard() {
        Executors.newSingleThreadExecutor().submit(() -> {
            while (true) {
                try {
                    //要么key达到1千个，要么达到1秒，就汇总上报给etcd一次
                    List<HotKeyModel> tempModels = new ArrayList<>();
                    Queues.drain(queue, tempModels, 1000, 1, TimeUnit.SECONDS);
                    if (CollectionUtils.isEmpty(tempModels)) {
                        continue;
                    }
                    //将热key推到dashboard
                    DashboardHolder.flushToDashboard(FastJsonUtils.convertObjectToJSON(tempModels));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
